﻿using System.Linq;
using System.Text.RegularExpressions;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;

namespace ScoutersLog.DataAccess.Persistence
{
    public class DbCaseTableNameConvention : IClassConvention
    {
        public void Apply(IClassInstance instance)
        {
            string tableName = Regex.Matches(instance.TableName, "[A-Z][a-z]+")
                .OfType<Match>()
                .Select(match => match.Value)
                .Aggregate((acc, b) => acc + "_" + b)
                .TrimStart('_');
            if (tableName.EndsWith("y"))
            {
                tableName = tableName.Substring(0, tableName.Length - 1) + "ies";
            }
            else
            {
                tableName += "s";
            }
            instance.Table(tableName);
        }
    }
}
